package com.estronger.shopmanage.base;

import android.Manifest;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Inputtips.InputtipsListener;
import com.amap.api.services.help.Tip;
import com.android.tu.loadingdialog.LoadingDailog;
import com.estronger.shopmanage.gaodemap.GPSNavigation;
import com.estronger.shopmanage.gaodemap.LocationActivity;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.order.until.ActivityCollector;
import com.estronger.shopmanage.ui.order.until.LoadingDialog2;
import com.estronger.shopmanage.utils.NetUtils;
import com.estronger.shopmanage.utils.PermissionUtils;
import com.estronger.shopmanage.utils.Toast;
import com.google.gson.Gson;
import com.lidroid.xutils.http.RequestParams;
import com.tbruyelle.rxpermissions2.Permission;

import java.io.File;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class BaseActivity extends FragmentActivity implements InputtipsListener {

    public LoadingDailog mDialog;
    public LoadingDialog2 mDialog2;
    public static BaseActivity activity;
    protected static Gson gson;
    protected long lastTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initLocaleLanguage();
        ActivityCollector.addActivity(this, getClass());
        // 定义所有子类的执行顺序
        gson = new Gson();
        lastTime = System.currentTimeMillis();
        init();// 第一步
        initView();// 第二步
        initAction();// 第三步
    }
    protected void init() {
    }

    protected void initView() {
    }

    protected void initAction() {
    }

    @Override
    protected void onResume() {
        //JPushInterface.onResume(this);
        super.onResume();
    }

    @Override
    protected void onPause() {
        //JPushInterface.onPause(this);
        super.onPause();
    }
    @Override
    protected void onStart(){
        super.onStart();
        Log.e("控制器",this.getClass().toString());
    }

    public void onBackViewClick(View view) {
        this.finish();
    }

    protected void setOnFocusChangeListener(EditText edit, final View view) {
        edit.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                view.setPressed(hasFocus);
            }
        });

    }

    // 为子类准备一个联网类，具体联网成功和失败都由子类来做处理
    public NetManager netManager = new NetManager() {
        @Override
        public void onNetWorkSuccess(int code, String result) {
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }
            onNetSuccess(code, result);
        }

        @Override
        public void onNetWorkErorr(int code, String result) {
            if (mDialog != null && mDialog.isShowing()) {
                mDialog.dismiss();
            }
            if (!NetUtils.isNetworkConnected(BaseActivity.this)) {
                Toast.show(BaseActivity.this, "当前无网络链接！", 2000);
                return;
            } else {
                Toast.show(BaseActivity.this, result, Toast.LENGTH_SHORT);
                onNetErorr(code, result);
            }
        }

        @Override
        public void onIMGSuccess(int code, String result) {
            onNetIMGSuccess(code, result);
        }

        ;

        @Override
        public void onGetSuccess(File result) {
            getAodioSuccess(result);
        }
    };

    public void connect(RequestParams params, final int code) {
        netManager.setTimeOut(60);
        netManager.connectWork(params, code);
    }

    protected void getAodioSuccess(File result) {

    }

    public void updateIMG(RequestParams params, final int code) {
        netManager.updateIMG(params, code);
    }

    public void uploadVideo(RequestParams params,int code){
        netManager.uploadVideo(params,code);
    }

    protected void onNetIMGSuccess(int code, String result) {


    }

    protected void onNetErorr(int code, String msg) {

    }

    protected void onNetSuccess(int code, String result) {
    }


    // 全局的loadingDialog
    protected void showDialog(String msg, boolean cancelable) {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
        LoadingDailog.Builder loadBuilder = new LoadingDailog.Builder(this)
                    .setMessage(msg)
                    .setCancelable(cancelable)
                    .setCancelOutside(false);
        mDialog = loadBuilder.create();
        mDialog.show();
    }

    // 全局的loadingDialog
    protected void dimssDialog() {
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    // 全局的loadingDialog
    protected void showDialog2(String msg, boolean cancelable) {
        if (mDialog2 != null && mDialog2.isShowing()) {
            mDialog2.setText(msg);
            mDialog2.setCancelable(cancelable);
            return;
        }
        if (mDialog2 == null) {
            mDialog2 = new LoadingDialog2(BaseActivity.this);
        }
        mDialog2.setText(msg);
        mDialog2.setCancelable(cancelable);
        mDialog2.show();
    }

    // 全局的loadingDialog
    protected void dimssDialog2() {
        if (mDialog2 != null && mDialog2.isShowing()) {
            mDialog2.dismiss();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollector.removeActivity(this);
        if (mDialog != null && mDialog.isShowing()) {
            mDialog.dismiss();
        }
    }

    // 获取路径中的Uri
    public String getRealPathFromURI(Uri contentUri) {
        String res = null;
        String[] proj = {MediaColumns.DATA};
        Cursor cursor = getContentResolver().query(contentUri, proj, null,
                null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
            res = cursor.getString(column_index);
        }
        cursor.close();
        return res;
    }

    // 展示货物条件的动画
    protected void valueAnim(int startHeight, int endHeight, final View v) {
        if (v == null)
            return;
        ValueAnimator animator = ValueAnimator.ofInt(startHeight, endHeight);
        animator.addUpdateListener(new AnimatorUpdateListener() {

            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int value = (Integer) animation.getAnimatedValue();
                LayoutParams params = v.getLayoutParams();
                params.height = value;
                v.setLayoutParams(params);
            }
        });
        animator.setDuration(800);
        animator.start();
    }

    // 搜索地址成功后的回调
    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        if (rCode == 0) {// 正确返回
            if (tipList.size() > 0) {
                Tip tip = tipList.get(0);
                String name = tip.getName();
                // String address = tip.getDistrict();
                double lat = tip.getPoint().getLatitude();
                double lng = tip.getPoint().getLongitude();
                // 这里就需要lookaddress那一段代码
                lookAddress(name, lat + "", lng + "");
            } else {
                Toast.show(this, "未搜索到详细地址\n注意地址需准确 省-市-区-街道", 2000);
            }
        } else {
            Toast.show(this, "未搜索到数据\n注意地址必需准确 省-市-区-街道", 2000);
        }
    }

    private Inputtips inputTips;

    public void search(String keyWord) {
        inputTips = new Inputtips(this, this);
        if (keyWord.equals("")) {
            return;
        }
        // 第一个参数表示提示关键字，第二个参数默认代表全国，也可以为城市区号
        try {
            inputTips.requestInputtips(keyWord, null);// MyApplication.province
        } catch (com.amap.api.services.core.AMapException e) {
            e.printStackTrace();
        }
    }

    // 查看地图
    private void lookAddress(String destination, String des_latitude,
                             String des_longitude) {
        Intent intent = new Intent(this, GPSNavigation.class);
        Bundle bundle = new Bundle();

        bundle.putString("dep_longitude", des_longitude);
        bundle.putString("dep_latitude", des_latitude);
        bundle.putString("departure", destination);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void guideMap2(View v) {
        TextView tv = (TextView) v;
        String add = tv.getText().toString();
        if (!"".equals(add)) {
            search(add);
        } else {
            Toast.show(this, "客户地址为空.不能导航", 2000);
        }
    }

    // 开始导航
    public void guideMap(final View v) {
        PermissionUtils.getInstance().requestPromisssions(this, new PermissionUtils.AcceptListener() {
                    @Override
                    public void grante() {
                        TextView tv = (TextView) v;
                        String add = tv.getText().toString().trim();
                        if(!add.equals("")) {
                            Intent intent = new Intent(BaseActivity.this, LocationActivity.class);
                            intent.putExtra("latitude", "");
                            intent.putExtra("location", add);
                            intent.putExtra("longtitude", "");
                            BaseActivity.this.startActivityForResult(intent, 8889);
                        } else {
                            Toast.show(BaseActivity.this, "客户地址为空.不能导航", 2000);
                        }
                    }

                    @Override
                    public void denial(Permission permission) {

                    }

                    @Override
                    public void fail() {

                    }
                },  Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION);
    }

    // 验证手机号码格式是否正确
    public boolean isRightNumber(String number) {
        if (!TextUtils.isEmpty(number)) {
            Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
            Matcher m = p.matcher(number);
//			if(m.matches()||(number.contains("-")&&number.length()==12)){
//				return true;
//			}else{
//				Toast.show(this,"电话号码格式错误:" + number,2000);
//				return false;
//			}
            return true;
        } else {
            Toast.show(this, "电话号码不能为空", 2000);
            return false;
        }
    }

    public void registerJpush(){
//        JPushInterface.setAlias(this, MyApplication.phone_id,
//                new TagAliasCallback() {
//                    @Override
//                    public void gotResult(int arg0, String arg1,
//                                          Set<String> arg2) {
//                        // 进行判断，极光注册信息是否通过审核
//                        if (arg0 == 0) {
//                            Log.i("MM", "登录");
//                            MyApplication.jpush_id = JPushInterface
//                                    .getRegistrationID(BaseActivity.this);
//                        } else {
//                            Log.i("MM", "登录失败，请重新登录.");
//                            registerJpush();
//                        }
//                    }
//                });
    }

    //带动画效果带数据跳转并传回数据
    protected void startActivityResult(Class<?> targetClass, Bundle bundle, int ACTION) {
        Intent intent = new Intent(this, targetClass);
        intent.putExtras(bundle);
        this.startActivityForResult(intent, ACTION);
    }

    //带动画效果带数据跳转并传回数据
    protected void startActivityResult(Class<?> targetClass, Intent inst, int ACTION) {
        Intent intent = new Intent(this, targetClass);
        intent.putExtras(inst);
        this.startActivityForResult(intent, ACTION);
    }

    //带动画效果不带带数据跳转并传回数据
    protected void startActivityResult(Class<?> targetClass, int ACTION) {
        Intent intent = new Intent(this, targetClass);
        this.startActivityForResult(intent, ACTION);
    }

    private void initLocaleLanguage() {
        Resources resources = this.getResources();
        Configuration configuration = resources.getConfiguration();
        configuration.locale = Locale.CHINA;
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());//更新配置 }
    }
    //代码中设置沉浸式
    protected void setImmersive() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            int flagTranslucentNavigation = WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.flags |= flagTranslucentNavigation;
                window.setAttributes(attributes);
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            } else {
                Window window = getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                attributes.flags |= flagTranslucentStatus | flagTranslucentNavigation;
                window.setAttributes(attributes);
            }
        }
    }
}
